#include "up_treaty.h"
#include "include.h"
#include <string.h>
#include <zlog.h>
#include <config.h>
#include <cstdlib>
#include <time.h>
#include "app_main.h"
#include <time.h>
#include <stdint.h>
up_treaty::up_treaty()
{
    mp_dev_data = get_dev_data_ptr();
    assert(mp_dev_data);
    event_id = 0;

    log_up_treaty = zlog_get_category(ZLOG_CAG_UP_TY);
    assert(log_up_treaty != nullptr);
    std::srand(time(0));
    float r = (std::rand() % 100) / 0.01f; // 不推荐！分布不均、质量差
    for (int i = 0; i < MAX_RSP_NUM; i++)
    {
        int r = std::rand() % 100 / 0.01; // 不推荐！分布不均、质量差
        mp_dev_data->reg_rsp_status[i] = i;
        // mp_dev_data->reg_rsp_alpha_status[i] = i + 10;
        // mp_dev_data->reg_rsp_beta_status[i] = i + 20;
        // mp_dev_data->reg_rsp_gama_status[i] = i + 30;

        mp_dev_data->reg_rsp_alpha_valt[i] = i + 0.2;
        mp_dev_data->reg_rsp_bate_valt[i] = i + 0.3;
        mp_dev_data->reg_rsp_gama_valt[i] = i + 0.4;

        mp_dev_data->reg_rsp_alpha_result_valt[i] = i + 0.5;
        mp_dev_data->reg_rsp_bate_result_valt[i] = i + 0.6;
        mp_dev_data->reg_rsp_gama_result_valt[i] = i + 0.7;
    }

    mp_dev_data->reg_heart = 0x55aa;
    mp_dev_data->reg_test_count = 6;
    mp_dev_data->reg_alarm_count = 9;
    mp_dev_data->reg_status = 10;
    memcpy(mp_dev_data->reg_read_person_id, "1234567890", 10);

    mp_dev_data->reg_alarm_mode = 1;                   // 报警阈值模式	01 19//1，动态阈值;2，静态阈值
    mp_dev_data->reg_static_gamma_threshold = 1.1f;    // 静态gamma阈值	01 1a ~ 01 1b
    mp_dev_data->reg_static_beta_threshold = 2.1f;     // 静态beta阈值	01 1c ~ 01 1d
    mp_dev_data->reg_static_alpha_threshold = 3.1f;    // 静态alpha阈值	01 1e ~ 01 1f
    mp_dev_data->reg_static_gamma_severe = 4.1f;       // 静态Gamma严重阈值	01 20 ~ 01 21
    mp_dev_data->reg_static_beta_severe = 5.1f;        // 静态beta严重阈值	01 22 ~ 01 23
    mp_dev_data->reg_static_alpha_severe = 6.1f;       // 静态alpha严重阈值	01 24 ~ 01 25
    mp_dev_data->reg_dynamic_gamma_coff = 7.1f;        // 动态gamma系数	01 26 ~ 01 27
    mp_dev_data->reg_dynamic_beta_coff = 8.1f;         // 动态beta系数	01 28 ~ 01 29
    mp_dev_data->reg_dynamic_alpha_coff = 9.1f;        // 动态alpha系数	01 2a ~ 01 2b
    mp_dev_data->reg_dynamic_gamma_severe_coff = 10.1; // 动态Gamma严重系数	01 2c ~ 01 2d
    mp_dev_data->reg_dynamic_beta_severe_coff = 11.1f; // 动态beta严重系数	01 2e ~ 01 2f
    mp_dev_data->reg_dynamic_alpha_severe_coff = 12.1; // 动态alpha严重系数	01 30 ~ 01 31
}
/**
 * @brief 创建错误帧
 * @param vec_data 错误帧数据
 * @param Exception_Code 异常码
 * @param Function_Code 功能码
 * @return uint32_t 错误帧数据长度
 *
 * | 异常码（十六进制） | 名称                                        | 含义               | 可能原因                                        |
| ------------------ | ------------------------------------------- | ------------------ | ----------------------------------------------- |
| `0x01`             | **Illegal Function**                        | 非法功能                             | 请求的功能码不支持（如从站不支持 FC=0x10）      |
| `0x02`             | **Illegal Data Address**                    | 非法数据地址                | 寄存器地址超出范围（如访问 400001~499999 之外） |
| `0x03`             | **Illegal Data Value**                      | 非法数据值                           | 写入的值无效（如长度不对、值越界）              |
| `0x04`             | **Slave Device Failure**                    | 从站设备故障                    | 设备内部错误（如硬件故障、程序崩溃）            |
| `0x05`             | **Acknowledge**                             | 确认                                    | 命令已接收，但需长时间处理（少见）              |
| `0x06`             | **Slave Device Busy**                       | 从站设备忙                       | 设备正忙，无法处理请求（可稍后重试）            |
| `0x08`             | **Memory Parity Error**                     | 存储奇偶校验错误               | 存储器读写出错（较老设备）                      |
| `0x0A`             | **Gateway Path Unavailable**                | 网关路径不可用               | Modbus 网关问题（跨网络通信失败）               |
| `0x0B`             | **Gateway Target Device Failed to Respond** | 网关目标设备无响应 | 目标设备未响应网关请求                          |
 */
uint32_t up_treaty::create_error_frame(vector<uint8_t> &frame, uint8_t Exception_Code, uint8_t Function_Code)
{

    vec_temp.clear();
    frame.clear();
    // 创建数据包
    msb_push_u8_to_array(vec_temp, dev_type);
    msb_push_u8_to_array(vec_temp, Function_Code + 0x80);
    msb_push_u8_to_array(vec_temp, Exception_Code); // 数据域长度大于255时，长度为0xffff

    // 数据头
    msb_push_u16_to_array(frame, event_id);        // 事务处理标识符
    msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
    msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
    hzlog_info(log_up_treaty, frame.data(), frame.size());
    frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
    return frame.size();
}

uint32_t up_treaty::create_write_reg_frame(vector<uint8_t> &frame, uint16_t reg_addr_start, uint16_t reg_num)
{

    vec_temp.clear();
    frame.clear();
    // 创建数据包
    msb_push_u8_to_array(vec_temp, dev_type);
    msb_push_u8_to_array(vec_temp, OPS::WRITE);
    msb_push_u16_to_array(vec_temp, reg_addr_start); // 寄存器地址
    msb_push_u16_to_array(vec_temp, reg_num);        // 寄存器数量

    // 数据头
    msb_push_u16_to_array(frame, event_id);        // 事务处理标识符
    msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
    msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
    hzlog_info(log_up_treaty, frame.data(), frame.size());
    frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
    return frame.size();
}

/**
 * @brief 解析帧
 *
 * @param frame
 * @return uint32_t
 */
uint32_t up_treaty::classfy_parse_frame(vector<uint8_t> &frame, vector<uint8_t> &return_data)
{
    return_data.clear();
    if (frame.size() < TREATY_HEADE_LEN)
    {
        create_error_frame(return_data, ModbusExceptionCode::ILLEGAL_DATA_VALUE, OPS::READ);
        zlog_warn(log_up_treaty, "frame size is error");
        return 1;
    }
    event_id = frame[0] << 8 | frame[1];           // 事务标识符（Transaction ID）
    uint16_t data_len = frame[4] << 8 | frame[5];  // 长度（Length）
    dev_type = (DEV)frame[6];                      // 单元标识符（Unit ID）
    ops = (OPS)frame[7];                           // 功能码（Function Code）0x03 ;0x10
    uint16_t reg_id = frame[8] << 8 | frame[9];    // 起始地址（Start Address）
    uint16_t reg_len = frame[10] << 8 | frame[11]; // 寄存器数量
    zlog_info(log_up_treaty, "event_id=%d dev_type=0x%02d ops=%d reg_id=0x%04x reg_len=%d", event_id, dev_type, ops, reg_id, reg_len);

    if (data_len + TREATY_HEADE_LEN != frame.size())
    {
        create_error_frame(return_data, ModbusExceptionCode::ILLEGAL_DATA_VALUE, ops);
        zlog_warn(log_up_treaty, "data len is error");
        return 2;
    }
    switch (ops)
    {
    case PUSH:
        break;
    case READ:
        read_reg_value(return_data, reg_id, reg_len);
        zlog_info(log_up_treaty, "reply data reg_id=0x%04x reg_len=%d", reg_id, return_data.size());
        hzlog_info(log_up_treaty, return_data.data(), return_data.size());
        break;
    case WRITE:
        set_reg_value(frame, return_data, reg_id, reg_len);
        break;
    default:
        create_error_frame(return_data, ModbusExceptionCode::ILLEGAL_DATA_VALUE);
        zlog_warn(log_up_treaty, "ops is error");
        return 3;
        break;
    }

    return 0;
}

uint32_t up_treaty::read_reg_value(vector<uint8_t> &frame, const uint16_t reg_addr_start, const uint16_t reg_num)
{
    vec_temp.clear();
    frame.clear();

    uint16_t reg_addr = reg_addr_start;
    bool ok = true;

    zlog_info(log_up_treaty, "reg_addr=0x%04x ", reg_addr);
    std::vector<uint8_t> vec_data;
    uint16_t add = get_reg_value(vec_data, static_cast<DEV_REG>(reg_addr), reg_num);

    msb_push_u8_to_array(vec_temp, dev_type);
    msb_push_u8_to_array(vec_temp, ops);
    msb_push_u8_to_array(vec_temp, vec_data.size());
    vec_temp.insert(vec_temp.end(), vec_data.begin(), vec_data.end());

    if (add)
    {

        msb_push_u16_to_array(frame, event_id);        // 事务处理标识符
        msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
        msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
        hzlog_info(log_up_treaty, frame.data(), frame.size());
        frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
    }
    else
    {
        frame.clear();
        create_error_frame(frame, ModbusExceptionCode::ILLEGAL_DATA_ADDRESS, OPS::READ);
    }
    return frame.size();
}
uint16_t up_treaty::get_reg_value(vector<uint8_t> &vec_data, DEV_REG reg_addr, const uint16_t reg_num)
{
    uint16_t reg_size = 0;
    if (DEV_REG::HEART == reg_addr && 1 == reg_num)
    {
        zlog_info(log_up_treaty, "up_treaty : HEART CMD");
        msb_push_u16_to_array(vec_data, mp_dev_data->reg_heart);
        reg_size = 1;
    }
    else if (DEV_REG::SYNC_TIME <= reg_addr &&
             reg_addr <= DEV_REG::SYNC_TIME_END &&
             6 == reg_num)
    {
        zlog_info(log_up_treaty, "up_treaty : SYNC_TIME CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::SYNC_TIME));
        uint16_t num = reg_num;
        reg_size = 0;
        uint16_t *u16_ptr = mp_dev_data->reg_rtc_time;
        get_system_time(mp_dev_data->reg_rtc_time);
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset + i < 6)
            {
                msb_push_u16_to_array(vec_data, u16_ptr[offset + i]);
                // zlog_info(log_up_treaty, "Base Data start reg_addr=0x%04x offset=0x%04x,val =%d", reg_addr, offset + i, u16_ptr[offset + i]);
                reg_size += 1;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error ofsset %d(0-8)", offset + i);
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::TEST_COUNT <= reg_addr &&
             reg_addr <= DEV_REG::READ_PERSON_ID &&
             0 == ((uint16_t)reg_addr & 0x01) &&
             0 == ((uint16_t)reg_num & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : TEST_COUNT CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::TEST_COUNT));
        offset = offset >> 1; // 由于是使用2个寄存器表示一个值然，所以需要除以2
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        uint32_t *u32_ptr = &mp_dev_data->reg_test_count;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset + i < 8)
            {
                if (offset + i < 3)
                {
                    msb_push_u32_to_array(vec_data, u32_ptr[offset + i]);
                    // zlog_info(log_up_treaty, "Base Data start reg_addr=0x%04x offset=0x%04x,val =%d", reg_addr, offset + i, u32_ptr[offset + i]);
                }
                else
                {
                    msb_push_array_to_array(vec_data, (uint8_t *)(u32_ptr + offset + i), sizeof(uint32_t));
                    zlog_info(log_up_treaty, "Base Data start reg_addr=0x%04x offset=0x%04x,str =%s", reg_addr, offset + i, (char *)&u32_ptr[offset + i]);
                }
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error ofsset %d(0-8)", offset + i);
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::ALARM_MODE <= reg_addr &&
             reg_addr <= DEV_REG::DYNAMIC_ALPHA_SEVERE_COEF &&
             0 == ((uint16_t)reg_addr & 0x01) &&
             0 == ((uint16_t)reg_num & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : ALARM_MODE COFF CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::ALARM_MODE));
        offset = offset >> 1; // 由于是使用2个寄存器表示一个值然，所以需要除以2
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        uint32_t *u32_ptr = &mp_dev_data->reg_alarm_mode;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset + i < 0x0d)
            {
                msb_push_u32_to_array(vec_data, u32_ptr[offset + i]);
                // zlog_info(log_up_treaty, "THRESHOLD start reg_addr=0x%04x offset=0x%04x,val =%d", reg_addr, offset + i, u32_ptr[offset + i]);
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error ofsset %d(0-8)", offset + i);
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::REGS_START_RSP_STATUS <= reg_addr &&
             reg_addr <= DEV_REG::REGS_START_RSP_STATUS_MAX &&
             0 == ((uint16_t)reg_addr & 0x01) &&
             0 == ((uint16_t)reg_num & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : REGS_START_RSP_STATUS  CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::REGS_START_RSP_STATUS));
        offset = offset >> 1; // 由于是使用2个寄存器表示一个值然，所以需要除以2
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        uint32_t *u32_ptr = mp_dev_data->reg_rsp_status;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset < MAX_RSP_NUM)
            {
                msb_push_u32_to_array(vec_data, u32_ptr[offset + i]);
                // zlog_info(log_up_treaty, "RSP STATUS start reg_addr=0x%04x offset=0x%04x,val =%d", reg_addr, offset + i, u32_ptr[offset + i]);
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error");
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::REGS_START_ALPHA <= reg_addr &&
             reg_addr < DEV_REG::REGS_START_ALPHA_MAX &&
             0 == ((uint16_t)reg_addr & 0x01) &&
             0 == ((uint16_t)reg_num & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : REGS_START_ALPHA  CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::REGS_START_ALPHA));
        offset = offset >> 1; // 由于是使用2个寄存器表示一个值然，所以需要除以2
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset < MAX_RSP_NUM)
            {
                msb_push_float_to_array(vec_data, mp_dev_data->reg_rsp_alpha_valt[offset + i]);
                // zlog_info(log_up_treaty, "ALPHA start reg_addr=0x%04x offset=0x%04x,val =%f", reg_addr, offset + i, mp_dev_data->reg_rsp_alpha_valt[offset + i]);
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error");
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::REGS_START_BATE <= reg_addr && reg_addr < DEV_REG::REGS_START_BATE_MAX && 0 == ((uint16_t)reg_addr & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : REGS_START_BATE  CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::REGS_START_BATE));
        offset = offset >> 1; // 由于是使用2个寄存器表示一个值然，所以需要除以2
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset < MAX_RSP_NUM)
            {
                msb_push_float_to_array(vec_data, mp_dev_data->reg_rsp_bate_valt[offset + i]);
                // zlog_info(log_up_treaty, "BATE  start reg_addr=0x%04x offset=0x%04x,val =%f", reg_addr, offset + i, mp_dev_data->reg_rsp_bate_valt[offset + i]);
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error");
                reg_size = 0;
                break;
            }
        }
    }
    else if (DEV_REG::REGS_START_GAMA <= reg_addr &&
             reg_addr < DEV_REG::REGS_START_GAMA_MAX &&
             0 == ((uint16_t)reg_addr & 0x01))
    {
        zlog_info(log_up_treaty, "up_treaty : REGS_START_GAMA  CMD");
        uint32_t offset = (static_cast<uint32_t>(reg_addr) - static_cast<uint32_t>(DEV_REG::REGS_START_GAMA));
        offset = offset >> 1;
        uint16_t num = reg_num >> 1;
        reg_size = 0;
        for (uint16_t i = 0; i < num; i++)
        {
            if (offset < MAX_RSP_NUM)
            {
                msb_push_float_to_array(vec_data, mp_dev_data->reg_rsp_gama_valt[offset + i]);
                // zlog_info(log_up_treaty, "GAMA  start reg_addr=0x%04x offset=0x%04x,val =%f", reg_addr, offset + i, mp_dev_data->reg_rsp_gama_valt[offset + i]);
                reg_size += 2;
            }
            else
            {
                zlog_warn(log_up_treaty, "offset is error");
                reg_size = 0;
                break;
            }
        }
    }
    else
    {
        zlog_warn(log_up_treaty, "reg_addr is error");
        reg_size = 0;
    }
    if (!reg_size)
    {
        vec_data.clear();
        create_error_frame(vec_data, ModbusExceptionCode::ILLEGAL_DATA_VALUE, OPS::READ);
    }
    return reg_size;
}
uint16_t up_treaty::set_reg_value(vector<uint8_t> &vec_data, vector<uint8_t> &return_data, const uint16_t reg_start, const uint16_t reg_num)
{
    DEV_REG reg_addr = static_cast<DEV_REG>(reg_start);
    if (reg_addr == DEV_REG::SYNC_TIME && reg_num == 6 && 25 == vec_data.size())
    {
        mp_dev_data->reg_rtc_time[0] = vec_data[13] << 8 | vec_data[14];
        mp_dev_data->reg_rtc_time[1] = vec_data[15] << 8 | vec_data[16];
        mp_dev_data->reg_rtc_time[2] = vec_data[17] << 8 | vec_data[18];
        mp_dev_data->reg_rtc_time[3] = vec_data[19] << 8 | vec_data[20];
        mp_dev_data->reg_rtc_time[4] = vec_data[21] << 8 | vec_data[22];
        mp_dev_data->reg_rtc_time[5] = vec_data[23] << 8 | vec_data[24];

        // 设置时间
        char time_str[64] = {0};
        snprintf(time_str, sizeof(time_str), "date -s \"%d-%d-%d %d:%d:%d\"",
                 mp_dev_data->reg_rtc_time[0], mp_dev_data->reg_rtc_time[1], mp_dev_data->reg_rtc_time[2],
                 mp_dev_data->reg_rtc_time[3], mp_dev_data->reg_rtc_time[4], mp_dev_data->reg_rtc_time[5]);
        zlog_info(log_up_treaty, "set_reg_value time_str=%s", time_str);
        // time_t timestamp = 0;
        // if (!get_app_config_ptr()->datetime_to_timestamp(time_str, &timestamp))
        // {
        //     zlog_warn(log_up_treaty, "set_reg_value datetime_to_timestamp error");
        // }

        int ret = system(time_str);
        if (ret == 0)
        {
            zlog_warn(log_up_treaty, "hard clock update success");
            int ret = system("hwclock -w -f /dev/rtc0");
            if (ret == 0)
            {
                zlog_warn(log_up_treaty, "hard clock update success");
            }
            else
            {
                zlog_warn(log_up_treaty, "hard clock update failed");
            }
        }
        else
        {
            zlog_warn(log_up_treaty, "hard clock update failed");
        }

        // if (!get_app_config_ptr()->set_linux_sys_time(timestamp))
        // {
        //     zlog_warn(log_up_treaty, "set_reg_value set_linux_sys_time error");
        // }
        // else
        // {

        // }
        // 构建响应包，返回数据
        create_write_reg_frame(return_data, reg_start, reg_num);
        get_send_down_queue_ptr()->push(EVENT::SYNC_RTC_TIMESTAMP);
    }
    else
    {
        create_error_frame(return_data, ModbusExceptionCode::ILLEGAL_DATA_VALUE, OPS::WRITE);
        zlog_warn(log_up_treaty, "syc time data size or reg !=6 or cmd  is error data size =%d", vec_data.size());
    }
}

/**
 * @brief 构建响应状态数据自动推送包
 *
 * @param frame 输出的数据包
 * @param rsp_num 响应状态数量
 * @param dev_type 设备类型 0:本地数据；1：阿尔法；2：贝塔；3：伽马
 * @return uint16_t 数据域长度
 */
uint16_t up_treaty::build_rsp_status_data_packet(vector<uint8_t> &frame, const uint16_t rsp_num, const PUSH_DATA_TYPE data_type)
{
    vec_temp.clear();
    frame.clear();
    // 构建数据域
    std::vector<uint8_t> vec_data;
    uint32_t *data_ptr = nullptr;

    data_ptr = get_dev_data_ptr()->reg_rsp_status;

    if (nullptr != data_ptr)
    {

        // 1.第1个寄存器表明类型
        msb_push_u16_to_array(vec_data, static_cast<uint16_t>(data_type));

        // 2.第2,3个寄存器发送rsp使用状态bit
        // msb_push_u32_to_array(vec_data, get_dev_data_ptr()->reg_rsp_use_bit);

        //  3.发送rsp使用数据
        for (size_t i = 0; i < rsp_num; i++)
        {
            msb_push_u32_to_array(vec_data, data_ptr[i]);
        }
        // zlog_debug(log_up_treaty, "create_measure    1 : vec_data.size() = %d", vec_data.size());
        // 创建数据包
        msb_push_u8_to_array(vec_temp, get_dev_data_ptr()->reg_dev_type); // 表明当前设备类型C1，C2
        msb_push_u8_to_array(vec_temp, OPS::READ);
        msb_push_u8_to_array(vec_temp, vec_data.size() & 0xff); // 数据域长度大于255时，长度为0xffff

        vec_temp.insert(vec_temp.end(), vec_data.begin(), vec_data.end()); // 数据域
        // 数据头
        msb_push_u16_to_array(frame, ++event_id);      // 事务处理标识符
        msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
        msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
        frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
    }
    else
    {
        frame.clear();
        create_error_frame(frame, ModbusExceptionCode::ILLEGAL_DATA_ADDRESS, OPS::READ);
    }
}
// 构建测量结果自动推送数据包
uint16_t up_treaty::build_rsp_result_data_packet(vector<uint8_t> &frame, const uint16_t rsp_num, const PUSH_DATA_TYPE data_type)
{

    vec_temp.clear();
    frame.clear();
    // 构建数据域
    std::vector<uint8_t> vec_data;
    float *data_ptr = nullptr;
    if (PUSH_DATA_TYPE::BackgroundAlphaValue == data_type)
    {
        data_ptr = get_dev_data_ptr()->reg_rsp_alpha_valt;
        zlog_info(log_up_treaty, "PUSH_DATA_TYPE::BackgroundAlphaValue");
    }
    else if (PUSH_DATA_TYPE::BackgroundBetaValue == data_type)
    {
        zlog_info(log_up_treaty, "PUSH_DATA_TYPE::BackgroundBetaValue");
        data_ptr = get_dev_data_ptr()->reg_rsp_bate_valt;
    }
    else if (PUSH_DATA_TYPE::BackgroundGammaValue == data_type)
    {
        zlog_info(log_up_treaty, "PUSH_DATA_TYPE::BackgroundGammaValue");
        data_ptr = get_dev_data_ptr()->reg_rsp_gama_valt;
    }
    // else if (PUSH_DATA_TYPE::MeasurementAlphaValue == data_type)
    // {
    //     data_ptr = get_dev_data_ptr()->reg_rsp_alpha_result_valt;
    // }
    // else if (PUSH_DATA_TYPE::MeasurementBetaValue == data_type)
    // {
    //     data_ptr = get_dev_data_ptr()->reg_rsp_bate_result_valt;
    // }
    // else if (PUSH_DATA_TYPE::MeasurementGammaValue == data_type)
    // {
    //     data_ptr = get_dev_data_ptr()->reg_rsp_gama_result_valt;
    // }

    else
    {
        zlog_warn(log_up_treaty, "dev_type error");
    }

    if (nullptr != data_ptr)
    {
        // 1.第1个寄存器表明类型
        msb_push_u16_to_array(vec_data, static_cast<uint16_t>(data_type));
        // 2.第2,3个寄存器发送rsp使用状态bit
        // msb_push_u32_to_array(vec_data, get_dev_data_ptr()->reg_rsp_use_bit);
        // 3.发送rsp数据
        for (size_t i = 0; i < rsp_num; i++)
        {
            msb_push_float_to_array(vec_data, data_ptr[i]);
        }
        // zlog_debug(log_up_treaty, "create_measure    1 : vec_data.size() = %d", vec_data.size());
        // 创建数据包
        msb_push_u8_to_array(vec_temp, get_dev_data_ptr()->reg_dev_type); // 表明当前设备类型C1，C2
        msb_push_u8_to_array(vec_temp, OPS::READ);
        msb_push_u8_to_array(vec_temp, vec_data.size() & 0xff); // 数据域长度大于255时，长度为0xffff

        vec_temp.insert(vec_temp.end(), vec_data.begin(), vec_data.end()); // 数据域
        // 数据头
        msb_push_u16_to_array(frame, ++event_id);      // 事务处理标识符
        msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
        msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
        // hzlog_info(log_up_treaty, frame.data(), frame.size());
        frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
    }
    else
    {
        frame.clear();
        create_error_frame(frame, ModbusExceptionCode::ILLEGAL_DATA_VALUE, OPS::READ);
    }
}

/**
 * @brief 构建响应其他附加数据自动推送包
 *
 * @param frame 输出的数据包
 * @param dev_type 设备类型
 * @return uint16_t 数据域长度
 */
uint16_t up_treaty::build_rsp_others_data_packet(vector<uint8_t> &frame, const PUSH_DATA_TYPE data_type)
{
    vec_temp.clear();
    frame.clear();
    // 构建数据域
    std::vector<uint8_t> vec_data;

    // 1.第1个寄存器表明类型
    msb_push_u16_to_array(vec_data, static_cast<uint16_t>(data_type));

    // 2.第2个寄存器表明测试数量
    msb_push_u32_to_array(vec_data, get_dev_data_ptr()->reg_test_count);

    // 3.第3个寄存器表明报警数量
    msb_push_u32_to_array(vec_data, get_dev_data_ptr()->reg_alarm_count);

    // 4.第4个寄存器设备状态
    msb_push_u32_to_array(vec_data, get_dev_data_ptr()->reg_status);

    // 5. 第5个寄存器time
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[0]);
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[1]);
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[2]);
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[3]);
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[4]);
    msb_push_u16_to_array(vec_data, get_dev_data_ptr()->reg_rtc_time[5]);

    // 6.第6个寄存器表明数据数量
    msb_push_array_to_array(vec_data, (uint8_t *)get_dev_data_ptr()->reg_read_person_id, sizeof(get_dev_data_ptr()->reg_read_person_id));

    // 创建数据包
    msb_push_u8_to_array(vec_temp, get_dev_data_ptr()->reg_dev_type); // 表明当前设备类型C1，C2
    msb_push_u8_to_array(vec_temp, OPS::READ);
    msb_push_u8_to_array(vec_temp, vec_data.size() & 0xff); // 数据域长度大于255时，长度为0xffff

    vec_temp.insert(vec_temp.end(), vec_data.begin(), vec_data.end()); // 数据域
    // 数据头
    msb_push_u16_to_array(frame, ++event_id);      // 事务处理标识符
    msb_push_u16_to_array(frame, 0);               // 协议标识符0=Modbus TCP
    msb_push_u16_to_array(frame, vec_temp.size()); // 协议标识符0=Modbus TCP
    frame.insert(frame.end(), vec_temp.begin(), vec_temp.end());
}

/**
 * @brief 获取当前系统时间并保存到输入参数数组中
 *
 * 时间格式：time[0] = 年, time[1] = 月, time[2] = 日,
 *          time[3] = 时, time[4] = 分, time[5] = 秒
 *
 * @param time 指向长度为6的uint16_t数组，用于存储时间
 * @return int 成功返回1，失败返回0
 */
int up_treaty::get_system_time(uint16_t time[6])
{
    if (time == NULL)
    {
        zlog_warn(log_up_treaty, "time is nullptr");
        return 0; // 输入指针为空，失败
    }

    time_t raw_time;
    struct tm *local_time;

    // 获取当前时间戳
    if (::time(&raw_time) == ((time_t)-1))
    {
        zlog_warn(log_up_treaty, "time() is error");
        return 0; // 获取时间失败
    }

    // 转换为本地时间（考虑时区）
    local_time = localtime(&raw_time);
    if (local_time == NULL)
    {
        zlog_warn(log_up_treaty, "get_system_time : localtime error");
        return 0; // 转换失败
    }

    // 填充数组 (注意：tm结构体中的值需要调整)
    time[0] = (uint16_t)(local_time->tm_year + 1900); // 年份从1900开始计数
    time[1] = (uint16_t)(local_time->tm_mon + 1);     // 月份从0开始（0-11）
    time[2] = (uint16_t)local_time->tm_mday;          // 日期
    time[3] = (uint16_t)local_time->tm_hour;          // 小时
    time[4] = (uint16_t)local_time->tm_min;           // 分钟
    time[5] = (uint16_t)local_time->tm_sec;           // 秒

    zlog_info(log_up_treaty, "get_system_time : %d-%d-%d %d:%d:%d", time[0], time[1], time[2], time[3], time[4], time[5]);

    return 1; // 成功
}